from django.shortcuts import render
from django.shortcuts import HttpResponse
import json,time
from db.mydb import MyDBConnection
from db.dao.majors import Majors
from db.utils.dfutils import load_json_to_object
from db.utils.logutils import LogUtils


def majors_index(request):
    current = 1#如果用户不提供，默认看第一页
    pagesize = 5#如果用户不提供，默认每页5条
    if request.method == 'GET':  #大小写
        myDBConnection = MyDBConnection()
        current = request.GET.get("current")
        pagesize = request.GET.get("pagesize")
        print(f'1111 {request.GET.get("current")}')
        offset = (int(current) - 1) * int(pagesize) #计算每页的第一条编号
        majorss_json = myDBConnection.fetch_data_by_sql(f"select * from majors limit {offset},{pagesize}")
        msg = f'现在查看的是第{current}页，每页大小{pagesize}'
        print(majorss_json)
        code = 200
        rep_json =  {"code":code,"msg":msg,"majors":majorss_json}
    if bool(request.GET.get('json'))==True: #判定返回是json还是页面渲染
        return HttpResponse(json.dumps(rep_json), content_type="application/json")
    else:
        return render(request, "majors/index.html", rep_json)


def majors_add(request):
    data = request.body.decode("utf-8")
    # print(type(data))
    myDBConnection =MyDBConnection()
   # majors_json_obj = json.loads(data)
    majors_json_obj=json.loads(data)
    print(majors_json_obj)
    majors = load_json_to_object(majors_json_obj,Majors())
    print(type(majors))
    myDBConnection.insert_entity(majors)
    pname = majors.m_name
    print(pname)

    # ------------日志记录开始 ，使用自定义日志记录器LogUtils.log----------
    path_name = 'd:\logs'
    current_time = time.localtime(time.time())

    current_time_str = time.strftime('%Y-%m-%d', current_time)  # 参数2为格式化字符串
    print(current_time_str)
    file_name = current_time_str + '_majors.log'
    LogUtils.log(path_name, file_name,majors.format_str())
    # LogUtils.log(path_name,file_name)


    msg = f"{pname}用户添加成功"
    code = 200
    rep_json = {"code":code,"msg":msg}
    return HttpResponse(json.dumps(rep_json,ensure_ascii=False))

def get_majorById(request):
    mywhere = []
    m_id = request.GET.get("m_id")
    myDBConnection = MyDBConnection()  # 连接数据库


    # 获取教育经历记录列表
    major_json = myDBConnection.fetch_data_by_sql(
        f"select * from majors where m_id ='{m_id}'  ")
    code = 200
    msg = f'现在查看的是受{m_id}成功'
    rep_json = {"code": code, "msg": msg, "major": major_json}
    if bool(request.GET.get('json')) == True:
        return HttpResponse(json.dumps(rep_json, ensure_ascii=False), content_type="application/json")
    else:
        return render(request, "player/index.html", rep_json)